//
//  ChangePhoneVc.swift
//  Pods
//
//  Created by eme on 2017/4/6.
//
//

import UIKit
import UtilCore
import RickonCore

class ChangePhoneVc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var phoneLabel: UILabel!
    
    @IBOutlet weak var orderTextField: UITextField!
    
    @IBOutlet weak var NextButton: UIButton!
    
    @IBOutlet weak var getOrderButton: UIButton!
    
    @IBOutlet weak var ybd_Label: UILabel!
    /*----------------------------   自定义属性区域    ----------------------------*/
    var changeMessage:String?
    
    var phone:String?
    
    var govm:GetOrderViewModel?
    
    var ckvm:CheckCodeViewModel?
    
    
    /// 计时器
    var countdownTimer: Timer?
    var remainingSeconds: Int = 0 {
        willSet {
            getOrderButton.setTitle("\(newValue)秒后重新获取", for: .normal)
            
            if newValue <= 0 {
                getOrderButton.setTitle("重新获取验证码", for: .normal)
                isCounting = false
            }
        }
    }
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ChangePhoneVc.updateTime(_:)), userInfo: nil, repeats: true)
                
                remainingSeconds = 60
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
            }
            
            getOrderButton.isEnabled = !newValue
        }
    }
    
    func updateTime(_ timer: Timer) {
        remainingSeconds -= 1
    }
    
    /****************************Storyboard 绑定方法区域****************************/
    @IBAction func nextStep(_ sender: UIButton) {
        
        if let mobel = phone{
            self.ckvm?.code = orderTextField.text!
            self.ckvm?.type = "reset"
            self.ckvm?.checkCode.onNext(mobel)
        }
        self.view.endEditing(true)
    }
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        if changeMessage == "修改登录密码"{
            self.title = "修改登录密码"
        }else{
            self.title = "修改绑定手机"
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setUpTextField()
        self.setupBtn()
        self.setUpGetOrderButton()
        self.setUpPhoneLabel()
        
        self.getOrderButton.rx.tap.subscribe(onNext:{ _ in
            
            
            self.govm?.type = "reset"
            
            if let mobel = self.phone{
                
                self.govm?.getOrder.onNext(mobel)
                
            }
            self.view.endEditing(true)
            
        }).addDisposableTo(disposeBag)
        self.phoneLabel.normal_fontSize(14)
        self.ybd_Label.normal_fontSize(16)
        orderTextField.font = UIFont(name: Theme.font.light, size: 15)
        getOrderButton.titleLabel?.normal_fontSize(13)
        NextButton.titleLabel?.bold_fontSize(17)
    }
    func setUpGetOrderButton(){
        getOrderButton.backgroundColor = UIColor.clear
        getOrderButton.setTitleColor(Theme.sansa.ChangePhone.CodeBtn_Title_Normal, for: .normal)
        getOrderButton.setTitleColor(Theme.sansa.ChangePhone.CodeBtn_Title_Disabled, for: .disabled)
        getOrderButton.setBackgroundImage(Theme.sansa.ChangePhone.CodeBtn_Bg_Disabled.getImage(), for: .disabled)
        getOrderButton.setBackgroundImage(Theme.sansa.ChangePhone.CodeBtn_Bg_Normal.getImage(), for: .normal)
    }
    func setUpTextField(){
        orderTextField.layer.borderColor = Theme.sansa.ChangePhone.textfield_Border.cgColor
        orderTextField.layer.borderWidth = 1
        
    }
    func setupBtn(){
        NextButton.layer.masksToBounds = true
        NextButton.layer.cornerRadius = 4
        NextButton.backgroundColor = UIColor.clear
        NextButton.changeBackgroundImage(Theme.btn.normal, highlightedColor: Theme.btn.highlighted, disabledColor: Theme.btn.disabled)
        
    }
    func setUpPhoneLabel(){
        if let model = phone{
            if model != ""{
                let startindex = model.index(model.startIndex, offsetBy: 3)
                let endIndex = model.index(model.startIndex, offsetBy: 7)
                self.phoneLabel.text = model.substring(to: startindex) + "****" + model.substring(from:endIndex)
            }
        }

    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        //是否可以下一步
        let valid = orderTextField.rx.text
            .map{($0?.characters.count)! >= 4}
            .shareReplay(1)
        valid
            .bindTo(NextButton.rx.isEnabled)
            .addDisposableTo(disposeBag)
        
        //-------------
        //获取验证码
        self.govm = GetOrderViewModel()
        
        govm?.backMessage.subscribe(onNext:{ data in
            if data == true{
                self.isCounting = true
            }
        }).addDisposableTo(disposeBag)
        
        govm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        //--------------------
        //验证验证码
        self.ckvm = CheckCodeViewModel()
        self.ckvm?.backMessage.subscribe(onNext:{ data in
            if data == true{
                if self.changeMessage == "修改登录密码"{
                    
                    if let mobel = self.phone{
                        _ = "resetpassword".openURL(["phone":mobel,"title":"修改密码"])
                    }
                    
                }else{
                    
                    _ = "buildnewphone".openURL()
                }
            }
            
        }).addDisposableTo(disposeBag)
        
        self.ckvm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
    }
}
